/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { X2DBeta } = require("./X2DInterface");
const { XTexture } = require("./XTexture");

function genMultilineText(s, size, maxw) {
    let lines = XTexture.splitText(s, size, maxw);
    return {
        lines: lines,
        width: maxw,
        height: lines.length * size,
        timeout: Date.now() + 3000,
    }
}
class XMultlineText {
    static SPLIT_HISTORY = {};
    static init_split(s, size, maxw) {
        if (!(s in XMultlineText.SPLIT_HISTORY)) {
            XMultlineText.SPLIT_HISTORY[s] = {};
        }
        if (!(size in XMultlineText.SPLIT_HISTORY[s])) {
            XMultlineText.SPLIT_HISTORY[s][size] = {};
        }
        if (!(maxw in XMultlineText.SPLIT_HISTORY[s][size])) {
            XMultlineText.SPLIT_HISTORY[s][size][maxw] = genMultilineText(s, size, maxw);
        }

        return XMultlineText.SPLIT_HISTORY[s][size][maxw];
    }
    static height(s, size, maxw) {
        let mt = XMultlineText.init_split(s, size, maxw);
        return mt.lines.length * size;
    }
    static draw(s, size, maxw, x, y, sw = 1, sh = 1, ra = 0, ox = -1, oy = -1, c = 0xffffffff) {
        let mt = XMultlineText.init_split(s, size, maxw);
        let doy = oy;
        let dox = ox;
        for (let i = 0; i < mt.lines.length; i++) {
            if (oy == 0 || oy == -1) {
                doy = -i * size * sh;
            } else if (oy == -2) {
                doy = -i * size * sh + mt.height * sh / 2;
            } else if (oy == -3) {
                doy = -i * size * sh + mt.height * sh;
            } else {
                doy = -i * size * sh + oy;
            }
            if (ox == 0 || ox == -1) {
                dox = 0;
            } else if (ox == -2) {
                dox = mt.width * sw / 2;
            } else if (oy == -3) {
                dox = mt.width * sw;
            } else {
                dox = ox;
            }
            X2DBeta.drawText(mt.lines[i], size, x, y, sw, sh, ra, dox, doy, c);
        }
    }
}

module.exports = {
    XMultlineText
}